package com.ciwong.epaper.modules.me.ui;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.epaper.bean.Grade;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.me.adapter.BookDeskRecyclerViewAdapter;
import com.ciwong.epaper.modules.me.bean.BookDeskBean;
import com.ciwong.epaper.modules.me.bean.BookmarkBean;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.bean.RefreshNewBookDesk;
import com.ciwong.epaper.modules.me.bean.SubjectBean;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.msg.bean.Ad;
import com.ciwong.epaper.modules.msg.bean.WorkContent;
import com.ciwong.epaper.ui.BaseFragment;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DoubleClickCheckUtils;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.ContainerType;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.io.Serializable;
import java.util.List;


/**
 * 新版书桌
 * Created by keepon on 2018/8/6.
 */
public class NewBookDeskFragment extends BaseFragment implements OnRefreshListener, View.OnClickListener {
    private static final String TAG = "NewBookDeskFragment";
    RecyclerView mRecyclerView;
    private TextView mTvGotoResourceCenter;

    private BookDeskBean mBookDeskBean;
    private SwipeToLoadLayout mSwipeToLoadLayout;
    private Button mBtnRetry;


    private BookDeskRecyclerViewAdapter mBookDeskRecyclerViewAdapter;
    private LinearLayout mLlLoadFailed, mLlNoData;

    public static NewBookDeskFragment newInstance() {
        NewBookDeskFragment fragment = new NewBookDeskFragment();
        return fragment;
    }

    public NewBookDeskFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_new_book_desk, container, false);
        findViews(view);
        initEvent();
        init();
        registerBoradcastReceiver();
        EventBus.getDefault().register(this);
        loadLocalHomePageData();
        return view;
    }


    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(EpaperConstant.BROADCAST_GET_SERVICE_REFRESH_BOOK_DESK);
        //注册广播
        getActivity().registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            if (EpaperConstant.BROADCAST_GET_SERVICE_REFRESH_BOOK_DESK.equals(intent.getAction())) {
                //延时一秒去网络请求，不然可能服务器那边没刷新
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getBookDeskHomePageFromNet();
                    }
                }, 1000);

            }
        }
    };
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        }
    };

    private void unregisterReceiver() {
        if (mBroadcastReceiver != null)
            getActivity().unregisterReceiver(mBroadcastReceiver);
    }

    private void findViews(View view) {
        mLlNoData = view.findViewById(R.id.ll_no_data);
        mLlLoadFailed = view.findViewById(R.id.ll_load_failed);
        mTvGotoResourceCenter = view.findViewById(R.id.tv_go_to_resource_center);
        mSwipeToLoadLayout = view.findViewById(R.id.swipe_toLoad_layout);
        mBtnRetry = view.findViewById(R.id.btn_retry);
        mRecyclerView = view.findViewById(R.id.swipe_target);
    }

    private void initEvent() {
        mSwipeToLoadLayout.setOnRefreshListener(this);
        mTvGotoResourceCenter.setOnClickListener(this);
        mBtnRetry.setOnClickListener(this);

    }

    private void init() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mBookDeskRecyclerViewAdapter = new BookDeskRecyclerViewAdapter(mActivity, mBookDeskBean);
        mRecyclerView.setAdapter(mBookDeskRecyclerViewAdapter);
        mRecyclerView.setFocusable(false);
    }

    @Override
    public void onResume() {
        super.onResume();
//        getBookDeskHomePageFromNet();
    }

    public void onEventMainThread(RefreshNewBookDesk refreshNewBookDesk) {
        if (refreshNewBookDesk.isRefreshUnconditional()) {
            getAndSerializeClassList();
        } else {
            if (mSwipeToLoadLayout.getVisibility() != View.VISIBLE) {
                getAndSerializeClassList();
            }
        }

    }


    //加载本地的首页数据，包括科目和单元选中情况
    private void loadLocalHomePageData() {
        if (getParentFragment() != null && !getParentFragment().isHidden()) {
            showCricleProgress();
        }
        SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_DESK_HOME_PAGE, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                failed(data);
            }

            @Override
            public void failed(Object data) {
                getBookDeskHomePageFromNet();
            }

            @Override
            public void success(Object data) {
                try {
                    if (data != null) {
                        hideCricleProgress();
                        mBookDeskBean = (BookDeskBean) data;
                        mBookDeskRecyclerViewAdapter.updateData(mBookDeskBean, true);
                        boolean jiaoCaiTongBuAndKeWaiTuoZhanAllEmpty = isJctbAndKwtzAndDubAndAdsEmpty(mBookDeskBean.getSubject(), mBookDeskBean.getBookmark(), mBookDeskBean.getDubvideo(), mBookDeskBean.getAds());
                        if (jiaoCaiTongBuAndKeWaiTuoZhanAllEmpty) {
                            showContainerType(ContainerType.TYPE_NO_DATA);
                        } else {
                            showContainerType(ContainerType.TYPE_HAVE_DATA);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    boolean isJiaoCaiTongbuEmpty = false;
    boolean isKeWaiTuoZhanEmpty = false;
    boolean isDubVideoEmpty = false;
    boolean isAdsEmpty = false;

    public boolean isJctbAndKwtzAndDubAndAdsEmpty(List<SubjectBean> subjectBeanList, List<BookmarkBean> bookmarkBeanList,
                                                  List<WorkContent> dubvideo, List<Ad> ads) {

        //课外拓展没数据隐藏起来
        if (bookmarkBeanList == null || bookmarkBeanList.size() == 0) {
            isJiaoCaiTongbuEmpty = true;
        }
        //教材同步没数据隐藏起来
        if (subjectBeanList == null || subjectBeanList.size() == 0) {
            isKeWaiTuoZhanEmpty = true;
        }
        //配音没数据隐藏起来
        if (dubvideo == null || dubvideo.size() == 0) {
            isDubVideoEmpty = true;
        }
        //广告没数据隐藏起来
        if (ads == null || ads.size() == 0) {
            isAdsEmpty = true;
        }
        return isJiaoCaiTongbuEmpty && isKeWaiTuoZhanEmpty && isDubVideoEmpty && isAdsEmpty;
    }

    /**
     * 获取并缓存班级列表
     */
    private void getAndSerializeClassList() {
        MeDao.getInstance().getClassList(EApplication.BRAND_ID, new BaseCallBack() {
            @Override
            public void success(Object data) {
                final List<Clazz> clazzs = (List<Clazz>) data;
                Clazz clazz = EApplication.getInstance().getClazz();
                if (clazzs == null || clazzs.isEmpty()) {
                    clazz = null;
                } else {
                    int indexOf = clazzs.indexOf(clazz);
                    if (indexOf < 0) {
                        indexOf = 0;
                    }
                    clazz = clazzs.get(indexOf);
                }
                SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_DEFAULT, clazz);
                SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST, (Serializable) clazzs);

                EApplication.getInstance().setClazzs(clazzs);
                EApplication.getInstance().setClazz(clazz);
                getBookDeskHomePageFromNet();

            }

            @Override
            public void failed(int errorCode, Object data) {
                CWLog.d(TAG, "拉取班级列表失败:" + errorCode);
                hideCricleProgress();
                mSwipeToLoadLayout.setRefreshing(false);
                if (mBookDeskBean == null) {
                    showContainerType(ContainerType.TYPE_NO_NET_FAILED);
                }
            }

            @Override
            public void failed(Object data) {
                CWLog.d(TAG, "拉取班级列表失败:" + data);
                hideCricleProgress();
                mSwipeToLoadLayout.setRefreshing(false);
                if (mBookDeskBean == null) {
                    showContainerType(ContainerType.TYPE_NO_NET_FAILED);
                }
            }
        });
    }


    public void getBookDeskHomePageFromNet() {
        int gradeId = 0;
        if (EApplication.getInstance().getClazz() != null) {
            gradeId = EApplication.getInstance().getClazz().getGradeId();
        }
        EpaperDao.getInstance().getBookDeskHomePage(EApplication.BRAND_ID, gradeId, new BaseExtCallBack(getActivity()) {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                hideCricleProgress();
                mSwipeToLoadLayout.setRefreshing(false);
                if (mBookDeskBean == null) {
                    showContainerType(ContainerType.TYPE_NO_NET_FAILED);
                }
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
                hideCricleProgress();
                mSwipeToLoadLayout.setRefreshing(false);
                if (mBookDeskBean == null) {
                    showContainerType(ContainerType.TYPE_NO_NET_FAILED);
                }
            }

            @Override
            public void success(Object data) {
                hideCricleProgress();
                mSwipeToLoadLayout.setRefreshing(false);
                try {
                    if (data != null && data instanceof BookDeskBean) {
                        mBookDeskBean = (BookDeskBean) data;
                        mBookDeskRecyclerViewAdapter.updateData(mBookDeskBean, false);
                        boolean jiaoCaiTongBuAndKeWaiTuoZhanAllEmpty = isJctbAndKwtzAndDubAndAdsEmpty(mBookDeskBean.getSubject(), mBookDeskBean.getBookmark(), mBookDeskBean.getDubvideo(), mBookDeskBean.getAds());
                        if (jiaoCaiTongBuAndKeWaiTuoZhanAllEmpty) {
                            showContainerType(ContainerType.TYPE_NO_DATA);
                        } else {
                            showContainerType(ContainerType.TYPE_HAVE_DATA);
                        }
                    } else {
                        if (mBookDeskBean == null) {
                            showContainerType(ContainerType.TYPE_NO_NET_FAILED);
                        }
                    }
                } catch (Exception e) {

                }


            }
        });
    }

    private void showContainerType(ContainerType containerType) {
        if (containerType == ContainerType.TYPE_NO_NET_FAILED) {
            mSwipeToLoadLayout.setVisibility(View.GONE);
            mLlLoadFailed.setVisibility(View.VISIBLE);
            mLlNoData.setVisibility(View.GONE);
        } else if (containerType == ContainerType.TYPE_NO_DATA) {
            mSwipeToLoadLayout.setVisibility(View.GONE);
            mLlNoData.setVisibility(View.VISIBLE);
            mLlLoadFailed.setVisibility(View.GONE);
        } else {
            mSwipeToLoadLayout.setVisibility(View.VISIBLE);
            mLlNoData.setVisibility(View.GONE);
            mLlLoadFailed.setVisibility(View.GONE);
        }
    }


    @Override
    public void onRefresh() {
        if (NetworkUtils.isOnline()) {
            getBookDeskHomePageFromNet();
        } else {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.INSTANCE.toastCenterNoNetError();
                    mSwipeToLoadLayout.setRefreshing(false);
                }
            }, 300);
        }
    }


    @Override
    public void onClick(View v) {
        if (!DoubleClickCheckUtils.vertify500Duration()) {
            return;
        }
        int id = v.getId();
        if (id == R.id.tv_go_to_resource_center) {
            MeJumpManager.jumpToResourseCenterH5Activity(mActivity, R.string.go_back, getResources().getString(R.string.resource_center));
        } else if (id == R.id.btn_retry) {
            getBookDeskHomePageFromNet();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver();
        EventBus.getDefault().unregister(this);
    }


}